package com.ccit.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ccit.common.client.EmployeeClient;
import com.ccit.common.exception.GymException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.MD5;
import com.ccit.common.utils.RedisUtils;
import com.ccit.common.utils.TokenUtil;
import com.ccit.model.Admin;
import com.ccit.model.Employee;
import com.ccit.model.vo.admin.AdminVo;
import com.ccit.model.vo.employee.EmployeeVo;
import com.ccit.user.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "管理员账号操作")
@RestController
@RequestMapping("/user/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private EmployeeClient employeeClient;



    //登录功能
    @ApiOperation(value = "管理员登录")
    @PostMapping("/login")
    public Result Login(@RequestBody Admin admin) {
        log.info("admin==================>" + admin.toString());
        //定义结果集
        Map<String, Object> result = new HashMap<String, Object>();
        Admin admin1 = adminService.login(admin);
        log.info("admin1====================>" + admin1.toString());
        if (admin1 == null) {
            throw new GymException(202, "认证失败");
        } else {
            Map<String, Object> info = new HashMap<>();
            info.put("id", admin1.getId());
            info.put("name", admin1.getName());
            info.put("phone", admin1.getPhone());
            info.put("email", admin1.getEmail());
            String token = TokenUtil.createToken(admin1);
            result.put("token", token);
            result.put("info", info);
            return Result.ok(result);
        }
    }

    @GetMapping("/test")
    public Map<String, Object> getToken(String token) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", true);
        map.put("msg", "请求成功");
        return map;
    }


    //    @CacheEvict(value = "employee", allEntries = true)
    @ApiOperation(value = "注册管理员信息")
    @PostMapping("/register/{checkCode}")
    public Result addAdmin(@RequestBody Admin admin,
                           @PathVariable("checkCode") String checkCode) {

        //根据用户名查找该用户是否已存在
        String name = admin.getName();
        String phone = admin.getPhone();
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        List<Admin> phoneList = adminService.list(wrapper);
        wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        List<Admin> nameList = adminService.list(wrapper);
        wrapper.eq("email",admin.getEmail());
        List<Admin> emailList = adminService.list(wrapper);
        if (phoneList.size() > 0 && nameList.size() > 0 && emailList.size() > 0) {
            //如果已存在该用户
            throw new GymException(213, "该手机或姓名或邮箱已被使用");
        } else {
                String code = redisUtils.get("checkCode:" + admin.getEmail()).toString();
                if (code==null){
                    throw new GymException(211, "验证码超时");
                }
                if (checkCode.equals(code)) {
                    //当验证码正确时
                    admin.setPassword(MD5.encodeMsg(admin.getPassword()));
                    //初始化职员信息
                    Employee employee = new Employee();
                    employee.setName(admin.getName());
                    employee.setPhone(admin.getPhone());
                    Boolean save = adminService.saveEmployee(employee);
                    if (save) {
                        //添加职员失败
                        return Result.fail().message("添加职员出错啦!");
                    }
                    log.info("==============================>" + admin.toString());
                    //调用service
                    Boolean flag = adminService.save(admin);
                    if (flag) {
                        return Result.ok("注册成功");
                    } else {
                        return Result.fail();
                    }
                } else {
                    throw new GymException(210, "验证码错误");
                }

        }
    }


    @ApiOperation(value = "发送邮箱验证码")
    @GetMapping("/emailCheck/{email}")
    public Result sendEmailTargetAddress(@PathVariable("email") String email) throws Exception {
        String code = adminService.getCheckCode(email);
        System.out.println(code);
        if (code.length() > 0) {
            return Result.ok("验证码发送成功");
        } else {
            return Result.fail().message("验证码发送失败");
        }
    }

    @ApiOperation(value = "根据id逻辑删除管理员")
    @DeleteMapping("/remove/{id}")
    public Result removeAdminById(@PathVariable("id") Integer id) {
        boolean flag = adminService.removeById(id);
        if (flag) {
            return Result.ok("删除成功");
        } else {
            return Result.fail().message("删除失败");
        }
    }

    @ApiOperation(value = "修改管理员密码")
    @PutMapping("/updatePassword")
    public Result updateAdminPassword(@RequestBody AdminVo adminVo) {
        //获取前端验证码并判断是否有一致
        Integer frontCheckCode = adminVo.getCheckCode();
        System.out.println(frontCheckCode);
        try {
            Integer redisCheckCode = Integer.parseInt(redisUtils.get("checkCode:" + adminVo.getEmail()).toString());
            System.out.println(redisCheckCode);
            if (frontCheckCode.equals(redisCheckCode)) {
                //当验证码一致时
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("email", adminVo.getEmail());
                updateWrapper.set("password", MD5.encodeMsg(adminVo.getNewPassword()));
                boolean result = adminService.update(updateWrapper);
                if (result) {
                    return Result.ok("修改成功");
                } else {
                    return Result.fail().message(adminVo.getEmail() + "邮箱信息不存在");
                }
            } else {
                throw new GymException(210, "验证码错误");
            }
        } catch (Exception e) {
            throw new GymException(23005, "您还未获取验证码或者邮箱信息错误");
        }
    }

    @ApiOperation(value = "修改管理员信息")
    @PutMapping("/updateAdmin")
    public Result updateAdmin(@RequestBody AdminVo adminVo) {
        //获取前端验证码并判断是否有一致
        Admin admin = adminService.getById(adminVo.getId());
        EmployeeVo employee = new EmployeeVo();
        employee.setName(adminVo.getName());
        employee.setPhone(admin.getPhone());
        employee.setNewPhone(adminVo.getPhone());
        if (admin == null) {
            throw new GymException(202, "无此管理员");
        }
        if (!admin.getName().equals(adminVo.getName()) && adminVo.getName() != null) {
            admin.setName(adminVo.getName());
        }
        if (!admin.getEmail().equals(adminVo.getEmail()) && adminVo.getEmail() != null) {
            admin.setEmail(adminVo.getEmail());
        }
        if (!admin.getPhone().equals(adminVo.getPhone()) && adminVo.getPhone() != null) {
            admin.setPhone(adminVo.getPhone());
        }

        boolean result = adminService.updateById(admin);
        Result updateResult = employeeClient.updateEmployeeInfo(employee);
        if (result && updateResult.getCode() == 200) {
            return Result.ok("修改成功");
        } else {
            System.out.println("...........");
            System.out.println(admin);
            throw new GymException(203, "修改失败");
        }

    }
}
